#include "DownSampler.h"

void DownSampler::init()
{
	startwidth=0;
	startheight=0;
	endwidth=0;
	endheight=0;

	step=2.0f;

	compiled=0;

	cntlayers=0;

	textures=0;
	fbos=0;

	starttexbinded=0;
	endtexbinded=0;

	sizes = 0;
}

DownSampler::DownSampler()
{
	init();

}

DownSampler::DownSampler(int startwidth_,int startheight_,int endwidth_,int endheight_)
{
	init();

	startwidth = startwidth_;
	startheight = startheight_;
	
	endwidth = endwidth_;
	endheight = endheight_;

	Compile();
}

DownSampler::DownSampler(int startsize,int endsize)
{
	init();

	startwidth = startsize;
	startheight = startsize;
	
	endwidth = endsize;
	endheight = endsize;

	Compile();
}

void DownSampler::free()
{
	for(int i=0;i<cntlayers;++i)
	{
		delete textures[i];
		delete fbos[i];
	}

	delete[] textures;
	delete[] fbos;
	delete[] sizes;
}

DownSampler::~DownSampler()
{
	free();
}

void DownSampler::StartSize(int width, int height)
{
	startwidth = width;
	startheight = height;
	compiled = 0;
}

void DownSampler::EndSize(int width, int height)
{
	endwidth = width;
	endheight = height;
	compiled = 0;
}

void DownSampler::StartSize(int size)
{
	StartSize(size,size);
}

void DownSampler::EndSize(int size)
{
	EndSize(size,size);
}

void DownSampler::Step(float step_)
{
	step = step_;
	compiled = 0;
}

int DownSampler::Compile()
{
	if(cntlayers >0)
	{
		free();
	}

	cntlayers = 0;
	
	int curwidth = startwidth;
	int curheight = startheight;
	while(curwidth != endwidth && curheight != endheight)
	{
		curwidth = (int)((float)curwidth / step);
		curheight = (int)((float)curheight / step);

		if(curwidth<endwidth)
			curwidth = endwidth;

		if(curheight<endheight)
			curheight = endheight;

		cntlayers++;
	}

	sizes = new float[cntlayers * 2];

	textures = new Texture*[cntlayers];
	fbos = new Effect*[cntlayers];

	compiled = 1;
	return compiled;
}

void DownSampler::BindStartTexture(Texture *start)
{
	if(!compiled)
		Compile();

}

void DownSampler::BindEndTexture(Texture *end)
{
	if(!compiled)
		Compile();
}

int DownSampler::GetStartWidth()
{
	return startwidth;
}

int DownSampler::GetStartHeight()
{
	return startheight;
}

int DownSampler::GetEndWidth()
{
	return endwidth;
}

int DownSampler::GetEndHeight()
{
	return endheight;
}

int DownSampler::Process()
{
	if(!compiled)
		Compile();

	return 1;
}